﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebNavigationApi.Models;
using WebNavigationApi.Models.ViewModel;

namespace WebNavigationApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class VisitController : ControllerBase
    {
        private WNContext _context;
        public VisitController(WNContext context)
        {
            _context = context;
        }


        [Route("AddVisit")]
        [Authorize]
        [HttpGet]
        public IActionResult AddVisit(string bookMarkId)
        {
            var userID = User.Claims.Where(p => p.Type == "userID").FirstOrDefault().Value;
            var visit = new WN_VISIT()
            {
                ID = Guid.NewGuid().ToString("N"),
                BOOKMARK_ID = bookMarkId,
                USER_ID = userID,
                CREATETIME = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"),
            };
            _context.WN_VISIT.Add(visit);
            _context.SaveChanges();
            return Ok(new Result(true, 200, "保存成功", ""));

        }

        /// <summary>
        /// 获取时间区间内的站点访问量
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        [Route("GetVisitCount")]
        //[Authorize]
        [HttpGet]
        
        public IActionResult GetVisitCount(DateTime? startTime, DateTime? endTime)
        {
            var resultList = new List<BaseEchart>();
            var userID = User.Claims.Where(p => p.Type == "userID").FirstOrDefault().Value;
            var visitList = _context.WN_VISIT.ToList()
                .Where(p => p.USER_ID == userID)
                .WhereIf(p => Convert.ToDateTime(p.CREATETIME) > startTime, startTime != null)
                .WhereIf(p => Convert.ToDateTime(p.CREATETIME) < endTime, endTime != null)
                .GroupBy(p => p.BOOKMARK_ID).Select(p => new 
            {
                id = p.Key,
                value = p.Count(),
            });


            foreach(var item in visitList)
            {
                var result = new BaseEchart();
                result.name = _context.WN_BOOKMARK.Where(p => p.ID == item.id).FirstOrDefault().NAME;
                result.value = item.value;
                result.category = "访问站点数量统计";
                resultList.Add(result);
            }

            return Ok(new ResultList(true, 200, "", resultList.OrderByDescending(p=>p.value).ToArray(), resultList.Count()));

        }


        /// <summary>
        /// 获取时间区间内的访问类型
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="dateTime"></param>
        /// <returns></returns>

        [Route("GetVisitType")]
        [Authorize]
        [HttpGet]
        public IActionResult GetVisitType(DateTime? startTime, DateTime? endTime)
        {

            var userID = User.Claims.Where(p => p.Type == "userID").FirstOrDefault().Value;
        
            var resultList = _context.WN_VISIT.ToList()
                .Where(p=>p.USER_ID== userID)
                 .WhereIf(p => Convert.ToDateTime(p.CREATETIME) > startTime, startTime != null)
                   .WhereIf(p => Convert.ToDateTime(p.CREATETIME) < endTime, endTime != null)
               .Join(_context.WN_BOOKMARK, // the source table of the inner join
                  p => p.BOOKMARK_ID,        // Select the primary key (the first part of the "on" clause in an sql "join" statement)
                  q => q.ID,   // Select the foreign key (the second part of the "on" clause)
                  (p, q) => new { 
                    id=p.ID,
                    type = q.TYPE
                  })   
               .GroupBy(p=>p.type).Select(p => new BaseEchart
                  {
                      name = p.Key,
                      value = p.Count(),
                      category = "访问类型数量统计"
                  });
            return Ok(new ResultList(true, 200, "", resultList.OrderByDescending(p=>p.value).ToArray(), resultList.Count()));

        }





        [Route("GetDailyVisit")]
        [Authorize]
        [HttpGet]
        public IActionResult GetDailyVisit(DateTime? startTime, DateTime? endTime)
        {
            var userID = User.Claims.Where(p => p.Type == "userID").FirstOrDefault().Value;
            var resultList = _context.WN_VISIT.ToList()
                .Where(p => p.USER_ID == userID)
                .WhereIf(p => Convert.ToDateTime(p.CREATETIME) > startTime, startTime != null)
                .WhereIf(p => Convert.ToDateTime(p.CREATETIME) < endTime, endTime != null)
            .GroupBy(
            p => p.CREATETIME.Substring(0,10)

            )
            .Select(p => new BaseEchart
             {
                 name = p.Key,
                 value = p.Count(),
                 category = "每日访问量统计"
             });
            return Ok(new ResultList(true, 200, "", resultList.OrderBy(p => p.name).ToArray(), resultList.Count()));

        }
    }
}
